package com.hardroid.workload.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;

import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.util.Xml;

import com.hardroid.workload.workcalc.BebanKerja;
import com.hardroid.workload.workcalc.Employer;
import com.hardroid.workload.workcalc.ObsvDay;
import com.hardroid.workload.workcalc.ObsvProject;
import com.hardroid.workload.workcalc.WorkUnit;
import com.hardroid.workload.workcalc.ObsvProject.ProjectStatus;
import com.hardroid.workload.workcalc.Tally;

public class Singleton {

	public static ObsvProject currentProject;
	public static EmployerAdapter employerAdapter;
	public static ObsvDay todayReference;
	public static UnitAdapter unitAdapter;

	/** Save project
	 * @param newProject
	 * @return
	 */
	public static boolean saveProject(ObsvProject newProject) {
		// TODO Auto-generated method stub
		System.out.println("Save Project " + newProject.projectName);
		String a = writeXml(newProject);
		try {

			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {

				FileOutputStream os = new FileOutputStream(new File("/sdcard/",
						newProject.projectName + ".hrd"));
				OutputStreamWriter out = new OutputStreamWriter(os);
				out.write(a);
				out.close();
				System.out.println("Successfully out write");
				return true;
			} else {
				System.out.println("Cannot write file");
				return false;
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("exception write");
			e.printStackTrace();
		}
		return false;

	}

	/** Load project dari file ke memory
	 * @param context
	 * @param file
	 * @return
	 * @throws FileNotFoundException
	 */
	public static ObsvProject loadProject(Context context, File file)
			throws FileNotFoundException {
		FileInputStream fis = new FileInputStream(file);		
		
		currentProject = parseXML(fis);
		currentProject.projectName = getFileName(file);
		employerAdapter = new EmployerAdapter(context,
				Singleton.currentProject.lEmployer);
		
		unitAdapter = new UnitAdapter(context, Singleton.currentProject.lWorkUnit);
		return currentProject;
	}

	/** Menulis string yang telah diformat sesuai dengan format xml dari project
	 * @param project
	 * @return
	 */
	public static String writeXml(ObsvProject project) {
		XmlSerializer serializer = Xml.newSerializer();
		StringWriter writer = new StringWriter();
		try {
			serializer.setOutput(writer);
			serializer.startDocument("UTF-8", true);
//			System.out.println("Save project overiew");
			serializer.startTag("", "project");
			serializer.startTag("", "observer");
			serializer.text(project.observerName);
			serializer.endTag("", "observer");
			serializer.startTag("", "company");
			serializer.attribute("", "name", project.companyName);
			serializer.attribute("", "location", project.companyLocation);
			serializer.endTag("", "company");
			serializer.startTag("", "note");
			serializer.text(project.projectNotes);
			serializer.endTag("", "note");
			serializer.startTag("", "ntally");
			serializer.text(project.obsvDesc.nTally + "");
			serializer.endTag("", "ntally");
			serializer.startTag("", "gap");
			serializer.text(project.obsvDesc.obsvGap + "");
			serializer.endTag("", "gap");
			
			if (Singleton.currentProject.projectStatus== ProjectStatus.PROJECT_FINISHED){
				serializer.startTag("", "result");				
				serializer.endTag("", "result");	
			}
			
			if (Singleton.todayReference != null){
				
				ObsvDay day = Singleton.todayReference;
				//Log.i("Singleton", "Save today reference "+HardroidUtils.dateToSDate(day.obsvDate));
				serializer.startTag("", "refday");
				serializer.startTag("", "refobsvdate");
				serializer.text(day.getXMLSObsvDate());
				serializer.endTag("", "refobsvdate");
				serializer.startTag("", "refworkstart");
				serializer.text(day.getXMLSWorkStart());
				serializer.endTag("", "refworkstart");
				serializer.startTag("", "refworkend");
				serializer.text(day.getXMLSWorkEnd());
				serializer.endTag("", "refworkend");
				serializer.startTag("", "reftallies");
				for (Tally t : day.lTally) {
					serializer.startTag("", "reftally");
					serializer.startTag("", "refobsvtime"); 
					serializer.text(t.getXMLSObsvTime());
					serializer.endTag("", "refobsvtime");
					serializer.startTag("", "refstatus");
					serializer.text(t.getTallyStatus());
					serializer.endTag("", "refstatus");
					serializer.startTag("", "refdescription");
					serializer.text(t.description);
					serializer.endTag("", "refdescription");
					serializer.endTag("", "reftally");
				}
				serializer.endTag("", "reftallies");
				serializer.endTag("", "refday");
			}
			
			/*
			 * Save list of employer
			 */
			List<Employer> lEmployer = project.lEmployer;
			if (!lEmployer.isEmpty()) {
//				System.out.println("Save employer");
				serializer.startTag("", "employers");
				for (Employer e : lEmployer) {
					serializer.startTag("", "employer");
					serializer.attribute("", "name", e.name);
					serializer.attribute("", "division", e.division);
					serializer.attribute("", "unit", e.unit);
					serializer.attribute("", "job", e.job);
					serializer.attribute("", "gender", e.male+"");
					serializer.attribute("", "jabatan", e.structural+"");

					serializer.startTag("", "sheet");
					serializer.startTag("", "days");
					for (ObsvDay day : e.sheet.lObsvDay) {
						serializer.startTag("", "day");
						serializer.startTag("", "obsvdate");
						serializer.text(day.getXMLSObsvDate());
						serializer.endTag("", "obsvdate");
						serializer.startTag("", "workstart");
						serializer.text(day.getXMLSWorkStart());
						serializer.endTag("", "workstart");
						serializer.startTag("", "workend");
						serializer.text(day.getXMLSWorkEnd());
						serializer.endTag("", "workend");
						serializer.startTag("", "tallies");
						for (Tally t : day.lTally) {
							serializer.startTag("", "tally");
							serializer.startTag("", "obsvtime"); 
							serializer.text(t.getXMLSObsvTime());
							serializer.endTag("", "obsvtime");
							serializer.startTag("", "status");
							serializer.text(t.getTallyStatus());
							serializer.endTag("", "status");
							serializer.startTag("", "description");
							serializer.text(t.description);
							serializer.endTag("", "description");
							serializer.endTag("", "tally");
						}
						serializer.endTag("", "tallies");
						// Questionaire
						serializer.startTag("", "anggota");
						serializer.text(day.questionaire.anggotaBadanPos+"");
						serializer.endTag("", "anggota");
						serializer.startTag("", "pedal");
						serializer.text(day.questionaire.pedalKakiPos+"");
						serializer.endTag("", "pedal");
						serializer.startTag("", "tangan");
						serializer.text(day.questionaire.penggunaanTanganPos+"");
						serializer.endTag("", "tangan");
						serializer.startTag("", "koordinasi");
						serializer.text(day.questionaire.koordinasiMataPos+"");
						serializer.endTag("", "koordinasi");
						serializer.startTag("", "alat");
						serializer.text(day.questionaire.peralatanPos+"");
						serializer.endTag("", "alat");
						serializer.startTag("", "kecepatan");
						serializer.text(day.questionaire.tingkatKecepatanKerjaPos+"");
						serializer.endTag("", "kecepatan");
						serializer.startTag("", "tenaga");
						serializer.text(day.questionaire.tenagaPos+"");
						serializer.endTag("", "tenaga");
						serializer.startTag("", "sikap");
						serializer.text(day.questionaire.sikapKerjaPos+"");
						serializer.endTag("", "sikap");
						serializer.startTag("", "gerakan");
						serializer.text(day.questionaire.gerakanKerPos+"");
						serializer.endTag("", "gerakan");
						serializer.startTag("", "lelah");
						serializer.text(day.questionaire.kelelahanMataPos+"");
						serializer.endTag("", "lelah");
						serializer.startTag("", "cahaya");
						serializer.text(day.questionaire.cahayaBaik+"");
						serializer.endTag("", "cahaya");
						serializer.startTag("", "temperatur");
						serializer.text(day.questionaire.temperaturPos+"");
						serializer.endTag("", "temperatur");
						serializer.startTag("", "atmosfer");
						serializer.text(day.questionaire.atmosferPos+"");
						serializer.endTag("", "atmosfer");
						serializer.startTag("", "lingkungan");
						serializer.text(day.questionaire.keadaanLingPos+"");
						serializer.endTag("", "lingkungan");
						serializer.startTag("", "hambatan");
						serializer.text(day.questionaire.hambatanValue+"");
						serializer.endTag("", "hambatan");						
						serializer.endTag("", "day");
					}
					serializer.endTag("", "days");
					serializer.endTag("", "sheet");

					// save beban kerja
					serializer.startTag("", "bebankerja");
					serializer.attribute("", "bebanhariantinggi", e.bebanKerja.getFaktorBebanHarianTinggi()+"");
					serializer.attribute("", "bebanharianrata2", e.bebanKerja.getFaktorBebanHarianRata2()+"");
					serializer.attribute("", "bebanharianrendah", e.bebanKerja.getFaktorBebanHarianRendah()+"");
					serializer.attribute("", "bebanbulanantinggi", e.bebanKerja.getFaktorBebanBulananTinggi()+"");
					serializer.attribute("", "bebanbulananrata2", e.bebanKerja.getFaktorBebanBulananRata2()+"");
					serializer.attribute("", "bebanbulananrendah", e.bebanKerja.getFaktorBebanBulananRendah()+"");
					serializer.attribute("", "produktifminggu", e.bebanKerja.getProduktifNormalMinggu()+"");
					serializer.attribute("", "produktifbulan", e.bebanKerja.getProduktifNormalBulan()+"");
					serializer.attribute("", "produktiftahun", e.bebanKerja.getProduktifNormalTahun()+"");
					serializer.attribute("", "beban1tahun", e.bebanKerja.getBebanKerja1Tahun()+"");
					serializer.endTag("", "bebankerja");
					// save beban kerja
					
					serializer.endTag("", "employer");

				}
				serializer.endTag("", "employers");
			}
			
			/*
			 * Save list of work unit
			 */
			List<WorkUnit> lWork = project.lWorkUnit;
			if (!lWork.isEmpty()) {				
				serializer.startTag("", "workunits");
				for (WorkUnit l : lWork) {
					System.out.println(l + " is saved");
					serializer.startTag("", "workunit");
					serializer.attribute("", "unitname", l.getNamaResponden());					
					serializer.attribute("", "unitunit", l.getUnitKerja());
					serializer.attribute("", "unitjabatan", l.getJabatanResponden());					
					serializer.attribute("", "tingkatkesibukansaatambildata",WorkUnit.getTingkatKesulitanKode( l.getTingkatKesibukanSaatAmbilData())+"");
					serializer.attribute("", "jamkerjarendah", l.getJamKerjaEfektifPerHariRendah()+"");
					serializer.attribute("", "jamkerjarata2", l.getJamKerjaEfektifPerHariRata2()+"");
					serializer.attribute("", "jamkerjatinggi", l.getJamKerjaEfektifPerHariTinggi()+"");
					serializer.attribute("", "harikerjarendah", l.getHariKerjaPerBulanRendah()+"");
					serializer.attribute("", "harikerjarata2", l.getHariKerjaPerBulanRata2()+"");
					serializer.attribute("", "harikerjatinggi", l.getHariKerjaPerBulanTinggi()+"");
					for (int ii = 0; ii<12; ii++){
						serializer.attribute("", "bulan"+ii, WorkUnit.getTingkatKesulitanKode(l.tingkatKesibukanTahun[ii])+"");
					}
					
					serializer.startTag("", "bawahans");
					for (Employer bawahan : l.listOfRespondenDiBawahi){
						System.out.println(bawahan + " is added into "+l);
						serializer.startTag("", "bawahan");
						serializer.attribute("", "name", bawahan.name);
						serializer.attribute("", "division", bawahan.division);
						serializer.attribute("", "unit", bawahan.unit);
						serializer.attribute("", "job", bawahan.job);
						serializer.attribute("", "male", bawahan.male+"");
						serializer.attribute("", "structural", bawahan.structural+"");
						serializer.endTag("", "bawahan");
					}
					serializer.endTag("", "bawahans");				
					serializer.endTag("", "workunit");
				}
				serializer.endTag("", "workunits");
			}
			
					
			serializer.endTag("", "project");
			serializer.endDocument();
			return writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	/** Memparse XML dan membuat object {@link ObsvProject} yang berkesesuaian dengan format yang ada
	 * @param reader
	 * @return
	 */
	public static ObsvProject parseXML(InputStream reader) {
		XmlPullParser parser = Xml.newPullParser();
		// StringBufferInputStream reader = new
		// StringBufferInputStream(xmlString);

		ObsvProject project = new ObsvProject();
		boolean employersFound = false;

		try {
			// auto-detect the encoding from the stream
			parser.setInput(reader, null);
			int eventType = parser.getEventType();
			boolean done = false;

			ObsvDay day = null;
			Tally tally = null;
			Employer employer = null;
			Employer bawahan = null;
			WorkUnit workunit = null;			
			int bulanNth=0;
			int daynth = 0;

			while (eventType != XmlPullParser.END_DOCUMENT && !done) {
				String name = null;
				switch (eventType) {
				case XmlPullParser.START_DOCUMENT:
					System.out.println("Start loading data");
					break;
				case XmlPullParser.START_TAG:
					name = parser.getName();
//					System.out.println("Load " + name);

					// project overview
					if (!employersFound) {
						if (name.equalsIgnoreCase("employers")) {
							employersFound = true;
						}

						if (name.equalsIgnoreCase("observer")) {
							project.observerName = parser.nextText();
						} else if (name.equalsIgnoreCase("company")) {
							if (parser.getAttributeCount() == 2) {
								project.companyName = parser.getAttributeValue(
										"", "name");
								project.companyLocation = parser
										.getAttributeValue("", "location");
							}
						} else if (name.equalsIgnoreCase("note")) {
							project.projectNotes = parser.nextText();
						} else if (name.equalsIgnoreCase("ntally")) {
							project.obsvDesc.nTally = Integer.parseInt(parser
									.nextText());
						} else if (name.equalsIgnoreCase("gap")) {
							project.obsvDesc.obsvGap = Integer.parseInt(parser
									.nextText());
						}  else if (name.equalsIgnoreCase("result")) {
							project.projectStatus = ProjectStatus.PROJECT_FINISHED;
						}else if (name.equalsIgnoreCase("refday")){
							Singleton.todayReference = new ObsvDay();
							
						}else if (name.equalsIgnoreCase("refobsvdate")){
							Singleton.todayReference.setDate(parser.nextText());							
						}else if (name.equalsIgnoreCase("refworkstart")){
							Singleton.todayReference.setWorkStart(parser.nextText());							
						}else if (name.equalsIgnoreCase("refworkend")){
							Singleton.todayReference.setWorkEnd(parser.nextText());							
						}else if (name.equalsIgnoreCase("reftally")) {
//							System.out.println("reftally");
							tally = new Tally();
						} else if (name.equalsIgnoreCase("refobsvtime")) {
							try {
								tally.setTime(parser.nextText());
							} catch (Exception e) {
								e.printStackTrace();
							}
						} else if (name.equalsIgnoreCase("refstatus")) {
							tally.setTallyStatus(parser.nextText());
						} else if (name.equalsIgnoreCase("refdesc")) {
							tally.description = parser.nextText();
							
						}

					} else if (employersFound) {
						if (name.equalsIgnoreCase("employer")) {
							employer = new Employer();
							employer.name = parser
									.getAttributeValue("", "name");
							employer.division = parser.getAttributeValue("",
									"division");
							employer.unit = parser
									.getAttributeValue("", "unit");
							employer.job = parser.getAttributeValue("", "job");
							// load gender and jabatann disini
							String gender = parser.getAttributeValue("","gender");
							if (gender.equals("true")){
								employer.male = true;
							}else{
								employer.male = false;
							}
							String jabatan= parser.getAttributeValue("","jabatan");
							if (jabatan.equals("true")){
								employer.structural= true;
							}else{
								employer.structural= false;
							}
							project.lEmployer.add(employer);
							
						}

//						System.out.println("Load sheet");
						if (name.equalsIgnoreCase("sheet")) {

						} else if (name.equalsIgnoreCase("day")) {
							day = new ObsvDay(employer);
							day.dayNth = daynth;
							daynth++;
						} else if (name.equalsIgnoreCase("obsvdate")) {
							try {
								day.setDate(parser.nextText());
							} catch (Exception e) {
								e.printStackTrace();
							}
						} else if (name.equalsIgnoreCase("workstart")) {
							try {
								day.setWorkStart(parser.nextText());
							} catch (Exception e) {
								e.printStackTrace();
							} //
						} else if (name.equalsIgnoreCase("workstop")) {
							try {
								day.setWorkEnd(parser.nextText());
							} catch (Exception e) {
								e.printStackTrace();
							}
						} else if (name.equalsIgnoreCase("tally")) {
//							System.out.println("tally");
							tally = new Tally();
						} else if (name.equalsIgnoreCase("obsvtime")) {
							try {
								tally.setTime(parser.nextText());
							} catch (Exception e) {
								e.printStackTrace();
							}
						} else if (name.equalsIgnoreCase("status")) {
							tally.setTallyStatus(parser.nextText());
						} else if (name.equalsIgnoreCase("desc")) {
							tally.description = parser.nextText();
						}
						// questionaire
						else if (name.equalsIgnoreCase("kecepatan")) {
							day.questionaire.tingkatKecepatanKerjaPos = Integer.parseInt(parser.nextText());
						}
						else if (name.equalsIgnoreCase("anggota")) {
							day.questionaire.anggotaBadanPos= Integer.parseInt(parser.nextText());
						}
						else if (name.equalsIgnoreCase("pedal")) {
							day.questionaire.pedalKakiPos= Integer.parseInt(parser.nextText());
						}
						else if (name.equalsIgnoreCase("tangan")) {
							day.questionaire.penggunaanTanganPos= Integer.parseInt(parser.nextText());
						}
						else if (name.equalsIgnoreCase("koordinasi")) {
							day.questionaire.koordinasiMataPos= Integer.parseInt(parser.nextText());
						}
						else if (name.equalsIgnoreCase("alat")) {
							day.questionaire.peralatanPos= Integer.parseInt(parser.nextText());
						}
						else if (name.equalsIgnoreCase("tenaga")) {
							day.questionaire.tenagaPos= Integer.parseInt(parser.nextText());
						}
						else if (name.equalsIgnoreCase("sikap")) {
							day.questionaire.sikapKerjaPos= Integer.parseInt(parser.nextText());
						}
						else if (name.equalsIgnoreCase("gerakan")) {
							day.questionaire.gerakanKerPos= Integer.parseInt(parser.nextText());
						}
						else if (name.equalsIgnoreCase("lelah")) {
							day.questionaire.kelelahanMataPos= Integer.parseInt(parser.nextText());
						}
						else if (name.equalsIgnoreCase("cahaya")) {
							day.questionaire.cahayaBaik = Boolean.parseBoolean(parser.nextText());
						}
						else if (name.equalsIgnoreCase("temperatur")) {
							day.questionaire.temperaturPos= Integer.parseInt(parser.nextText());
						}
						else if (name.equalsIgnoreCase("atmosfer")) {
							day.questionaire.atmosferPos= Integer.parseInt(parser.nextText());
						}
						else if (name.equalsIgnoreCase("lingkungan")) {
							day.questionaire.keadaanLingPos= Integer.parseInt(parser.nextText());
						}
						else if (name.equalsIgnoreCase("hambatan")) {
							day.questionaire.hambatanValue= Integer.parseInt(parser.nextText());
						}
						// load beban kerja												
						else if (name.equalsIgnoreCase("bebankerja")){
							employer.bebanKerja.setFaktorBebanHarianTinggi(Float.parseFloat( parser.getAttributeValue(
									"", "bebanhariantinggi")));
							employer.bebanKerja.setFaktorBebanHarianRata2(Float.parseFloat( parser.getAttributeValue(
									"", "bebanharianrata2")));
							employer.bebanKerja.setFaktorBebanHarianRendah(Float.parseFloat( parser.getAttributeValue(
									"", "bebanharianrendah")));
							employer.bebanKerja.setFaktorBebanBulananTinggi(Float.parseFloat( parser.getAttributeValue(
									"", "bebanbulanantinggi")));
							employer.bebanKerja.setFaktorBebanBulananRata2(Float.parseFloat( parser.getAttributeValue(
									"", "bebanbulananrata2")));
							employer.bebanKerja.setFaktorBebanBulananRendah(Float.parseFloat( parser.getAttributeValue(
									"", "bebanbulananrendah")));							
							employer.bebanKerja.setProduktifNormalMinggu(Float.parseFloat( parser.getAttributeValue(
									"", "produktifminggu")));
							employer.bebanKerja.setProduktifNormalBulan(Float.parseFloat( parser.getAttributeValue(
									"", "produktifbulan")));
							employer.bebanKerja.setProduktifNormalTahun(Float.parseFloat( parser.getAttributeValue(
									"", "produktiftahun")));
							employer.bebanKerja.setBebanKerja1Tahun(Float.parseFloat( parser.getAttributeValue(
									"", "beban1tahun")));							
						}
						
						// cari workunits
						else if (name.equalsIgnoreCase("workunit")){
							System.out.println("Load WORK UNIT");
							workunit = new WorkUnit();
							bulanNth= 0;						
							workunit.setNamaResponden( parser.getAttributeValue(
									"", "unitname"));
					
							workunit.setUnitKerja( parser.getAttributeValue(
									"", "unitunit"));
					
							workunit.setJabatanResponden( parser.getAttributeValue(
									"", "unitjabatan"));
						
							workunit.setTingkatKesibukanSaatAmbilData(Integer.parseInt( parser.getAttributeValue(
									"", "tingkatkesibukansaatambildata")));
						
							workunit.setJamKerjaEfektifPerHariRendah(Integer.parseInt( parser.getAttributeValue(
									"", "jamkerjarendah")));
						
							workunit.setJamKerjaEfektifPerHariRata2(Integer.parseInt( parser.getAttributeValue(
									"", "jamkerjarata2")));
						
							workunit.setJamKerjaEfektifPerHariTinggi(Integer.parseInt( parser.getAttributeValue(
									"", "jamkerjatinggi")));
						
							workunit.setHariKerjaPerBulanRendah(Integer.parseInt( parser.getAttributeValue(
									"", "harikerjarendah")));
						
							workunit.setHariKerjaPerBulanRata2(Integer.parseInt( parser.getAttributeValue(
									"", "harikerjarata2")));
						
							workunit.setHariKerjaPerBulanTinggi(Integer.parseInt( parser.getAttributeValue(
									"", "harikerjatinggi")));

							for (int ii = 0;ii<12;ii++){
							workunit.tingkatKesibukanTahun[ii] = WorkUnit.convertFromCodeKesibukan(Integer.parseInt( parser.getAttributeValue(
									"", "bulan"+ii)));
							}
							bulanNth++;
							
						}		
						else if (name.equalsIgnoreCase("bawahan")){
							System.out.println("Load bawahan-bawahan");
							
							bawahan = new Employer();
							bawahan.name =  parser.getAttributeValue("", "name");
							bawahan.division=  parser.getAttributeValue("", "division");
							bawahan.job=  parser.getAttributeValue("", "job");
							bawahan.unit=  parser.getAttributeValue("", "unit");
							bawahan.male=  Boolean.parseBoolean(parser.getAttributeValue("", "male"));
							bawahan.structural=  Boolean.parseBoolean(parser.getAttributeValue("", "structural"));
							workunit.loadEmployerFromFile(project,bawahan);
						}																	
						// end if employer found
					}

					break;
				case XmlPullParser.END_TAG:
					name = parser.getName();
					// System.out.println("get end tag" + name);
					if (name.equalsIgnoreCase("sheet")) {
						// project.lObsvSheet.add(sheet);
					} else if (name.equalsIgnoreCase("day")) {
						employer.sheet.lObsvDay.add(day);
					} else if (name.equalsIgnoreCase("tally")) {
						day.lTally.add(tally);
					} else if (name.equalsIgnoreCase("reftally")) {
						Singleton.todayReference.lTally.add(tally);
					} else if (name.equalsIgnoreCase("workunit")){
						project.lWorkUnit.add(workunit);
						System.out.println(workunit);
					}

					break;
				}
				eventType = parser.next();
			}
		} catch (Exception e) {
			System.out.println("exception");
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		if (project.projectStatus!= ProjectStatus.PROJECT_FINISHED){
			project.projectStatus= ProjectStatus.PROJECT_NOT_FINISHED;
		}
		return project;
	}

	/** Get extension dari file
	 * @param file
	 * @return
	 */
	public static String getExtension(File file) {
		if (file.isFile()) {
			int dotIndex = file.toString().lastIndexOf(".");
			String extension = file.toString().substring(dotIndex + 1,
					file.toString().length());
			return extension;
		} else {
			return "";
		}
	}

	/** Get nama file dari file
	 * @param file
	 * @return
	 */
	public static String getFileName(File file) {
		if (file.isFile()) {
			int dotIndex = file.toString().lastIndexOf(".");
			int fileSeparatorIndex = file.toString()
					.lastIndexOf(File.separator);
			String fileName = file.toString().substring(fileSeparatorIndex + 1,
					dotIndex);
			return fileName;
		} else {
			return "";
		}

	}

	/** Memfilter ekstensi dari file
	 * @param file
	 * @return
	 */
	public static boolean filterExtension(File file) {
		String extension = getExtension(file);
		return extension.equalsIgnoreCase("hrd");

	}
	
	/** Mengecek apakah {@link Singleton#todayReference} sudah terload dengan baik
	 * @return true jika sudah terload dan today reference tanggalnya benar pada hari ini
	 */
	public static boolean isDayReferenceValid(){
		if (Singleton.todayReference!=null){
			if (!HardroidUtils.isDateToday(Singleton.todayReference.obsvDate)){			
				return false;
			}		
		}else {
			return false;
		}
		
		return true;
	}
	
	/** Menggenerate new today reference
	 * @param m1
	 * @param h1
	 * @param m2
	 * @param h2
	 */
	public static void generateNewReference(int m1, int h1, int m2, int h2){
		if (currentProject!=null){
			if (todayReference!=null){
				if (!HardroidUtils.isDateToday(todayReference.obsvDate)){
					// jika tidak null, tapi tidak benar, maka generate baru
					ObsvDay day = new ObsvDay();
					day.setWorkStart(h1,m1);
					day.setWorkEnd(h2, m2);
					day.generateObservationTime(currentProject.obsvDesc.nTally, currentProject.obsvDesc.obsvGap);
					todayReference = day;
				}
			}else{
				// jika today reference null, maka generate baru
				ObsvDay day = new ObsvDay();
				day.setWorkStart(h1,m1);
				day.setWorkEnd(h2, m2);
				day.generateObservationTime(currentProject.obsvDesc.nTally, currentProject.obsvDesc.obsvGap);				
				todayReference = day;
				//Log.i("Singleton", "Generated new reference "+HardroidUtils.dateToSDate( day.obsvDate));
			}
		}
	}
}
